package model

import (
	"fmt"
	"go.uber.org/zap"
	"zhejianglab/gin-apiserver/pkg/logger"

	"zhejianglab/gin-apiserver/pkg/setting"

	"github.com/jinzhu/gorm"

	// db package
	_ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

var db *gorm.DB

func init() {
	// read config
	sec, err := setting.Cfg.GetSection("database")
	if err != nil {
		logger.Log.Fatal("Fail to get section 'database'", zap.String("reason", err.Error()))
	}

	dbType := sec.Key("TYPE").String()
	dbConfig := "/data/ApiServer.db"
	if dbType == "mysql" {
		dbConfig = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
			setting.DataBaseUser,
			setting.PassWord,
			setting.Host,
			setting.DataBaseName)
	}
	//open a db connection
	db, err = gorm.Open(dbType, dbConfig)
	if err != nil {
		logger.Log.Warn(err.Error())
		panic("failed to connect database")
	}
	//Migrate the schema
	db.AutoMigrate(&UserInfo{})
	db.AutoMigrate(&AlgorithmInfo{})
	db.AutoMigrate(&JobInfo{})
	db.AutoMigrate(&DatasetInfo{})
	db.AutoMigrate(&DownloadInfo{})
	db.AutoMigrate(&ClueInfo{})
	db.AutoMigrate(&FileInfo{})
	db.AutoMigrate(&AlarmInfo{})
	db.AutoMigrate(&ConfigInfo{})
	db.AutoMigrate(&VideoInfo{})
}

// CloseDB close the datebase connection
func CloseDB() {
	defer db.Close()
}
